package com.fengmi.interceptor;

import cn.hutool.json.JSONUtil;
import com.fengmi.user.SysUser;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 作者：铁蛋
 * 时间：2021/10/23 14:26
 * 描述：永无Bug
 */
@Component
public class UserInfoInterceptor implements HandlerInterceptor {
    private static   ThreadLocal<SysUser> local=new ThreadLocal<>();


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头中获取用户信息
        String userInfo = request.getHeader("userInfo");
        SysUser sysUser = JSONUtil.toBean(userInfo, SysUser.class);
        if (sysUser!=null){
            local.set(sysUser);
        }


        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        local.remove();



    }
    public static  SysUser getUserInfo(){
        return local.get();
    }
}
